import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from pathlib import Path
import json

class MarkdownAttributeEditor:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Markdown属性编辑器")
        self.root.geometry("800x600")
        
        self.directory = None
        self.md_files = []
        self.current_file_index = 0
        self.attribute_entries = {}
        
        # 定义属性字段
        self.attributes = [
            "tags", "type", "actor_id", "name", "aliases", 
            "link", "罩杯", "风格", "气质", "体型", "演技"
        ]
        
        # 创建界面
        self.create_widgets()
    
    def create_widgets(self):
        # 顶部按钮框架
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=10)
        
        tk.Button(button_frame, text="选择目录", command=self.select_directory).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="保存当前文件", command=self.save_current_file).pack(side=tk.LEFT, padx=5)
        tk.Button(button_frame, text="批量保存所有文件", command=self.batch_save).pack(side=tk.LEFT, padx=5)
        
        # 文件导航框架
        nav_frame = tk.Frame(self.root)
        nav_frame.pack(pady=5)
        
        self.file_label = tk.Label(nav_frame, text="未选择目录")
        self.file_label.pack(side=tk.LEFT, padx=5)
        
        tk.Button(nav_frame, text="上一个", command=self.previous_file).pack(side=tk.LEFT, padx=5)
        tk.Button(nav_frame, text="下一个", command=self.next_file).pack(side=tk.LEFT, padx=5)
        
        # 属性编辑框架
        edit_frame = tk.Frame(self.root)
        edit_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 创建滚动框架
        canvas = tk.Canvas(edit_frame)
        scrollbar = ttk.Scrollbar(edit_frame, orient="vertical", command=canvas.yview)
        self.scrollable_frame = ttk.Frame(canvas)
        
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
        )
        
        canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        canvas.configure(yscrollcommand=scrollbar.set)
        
        canvas.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 创建属性输入字段
        self.create_attribute_fields()
    
    def create_attribute_fields(self):
        # 清空现有字段
        for widget in self.scrollable_frame.winfo_children():
            widget.destroy()
        
        # 创建属性输入字段
        for i, attr in enumerate(self.attributes):
            # 标签
            label = tk.Label(self.scrollable_frame, text=f"{attr}:")
            label.grid(row=i, column=0, sticky="w", padx=5, pady=5)
            
            # 输入框
            if attr in ["tags", "风格", "气质", "体型", "演技"]:
                # 多行文本框用于数组类型的属性
                entry = tk.Text(self.scrollable_frame, height=3, width=60)
                self.attribute_entries[attr] = entry
                entry.grid(row=i, column=1, padx=5, pady=5, sticky="ew")
            else:
                # 单行文本框用于简单属性
                entry = tk.Entry(self.scrollable_frame, width=60)
                self.attribute_entries[attr] = entry
                entry.grid(row=i, column=1, padx=5, pady=5, sticky="ew")
        
        # 配置列权重使输入框可以扩展
        self.scrollable_frame.columnconfigure(1, weight=1)
    
    def select_directory(self):
        self.directory = filedialog.askdirectory(title="选择包含Markdown文件的目录")
        if self.directory:
            self.load_md_files()
            if self.md_files:
                self.current_file_index = 0
                self.load_file_attributes()
            else:
                messagebox.showinfo("提示", "目录中没有找到Markdown文件")
    
    def load_md_files(self):
        self.md_files = []
        for file_path in Path(self.directory).rglob("*.md"):
            self.md_files.append(file_path)
        
        self.file_label.config(text=f"文件: 1/{len(self.md_files)}")
    
    def load_file_attributes(self):
        if not self.md_files:
            return
        
        file_path = self.md_files[self.current_file_index]
        self.file_label.config(text=f"文件: {self.current_file_index + 1}/{len(self.md_files)} - {file_path.name}")
        
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析front matter
        front_matter = self.parse_front_matter(content)
        
        # 填充属性值到输入框
        for attr in self.attributes:
            entry = self.attribute_entries[attr]
            
            # 清空当前内容
            if isinstance(entry, tk.Text):
                entry.delete(1.0, tk.END)
            else:
                entry.delete(0, tk.END)
            
            # 设置新值
            if attr in front_matter:
                value = front_matter[attr]
                if isinstance(value, list):
                    # 数组类型属性，每行一个元素
                    if isinstance(entry, tk.Text):
                        entry.insert(1.0, "\n".join(value))
                    else:
                        entry.insert(0, ", ".join(value))
                else:
                    # 简单属性
                    if isinstance(entry, tk.Text):
                        entry.insert(1.0, str(value))
                    else:
                        entry.insert(0, str(value))
    
    def parse_front_matter(self, content):
        """解析Markdown文件的front matter"""
        front_matter = {}
        
        # 匹配front matter（两个---之间的内容）
        match = re.search(r'^---\s*\n(.*?)\n---', content, re.DOTALL)
        if match:
            front_matter_text = match.group(1)
            
            # 解析YAML格式的front matter
            lines = front_matter_text.split('\n')
            current_key = None
            current_list = []
            
            for line in lines:
                line = line.strip()
                if not line:
                    continue
                
                # 处理键值对
                if ':' in line and not line.startswith(' '):
                    # 保存上一个列表（如果有）
                    if current_key and current_list:
                        front_matter[current_key] = current_list
                        current_list = []
                    
                    key, value = line.split(':', 1)
                    key = key.strip()
                    value = value.strip()
                    
                    if value.startswith('[') and value.endswith(']'):
                        # 数组格式
                        try:
                            # 尝试解析JSON数组
                            front_matter[key] = json.loads(value)
                        except:
                            # 简单分割
                            items = value[1:-1].split(',')
                            front_matter[key] = [item.strip() for item in items if item.strip()]
                    elif value.startswith('-'):
                        # YAML列表格式
                        current_key = key
                        current_list = [value[1:].strip()]
                    elif value:
                        # 简单值
                        front_matter[key] = value
                    else:
                        # 空值，可能是列表的开始
                        current_key = key
                        current_list = []
                elif line.startswith('- ') and current_key:
                    # 列表项
                    current_list.append(line[2:].strip())
                elif current_key and current_list:
                    # 续行（简化处理）
                    pass
            
            # 保存最后一个列表（如果有）
            if current_key and current_list:
                front_matter[current_key] = current_list
        
        return front_matter
    
    def save_current_file(self):
        if not self.md_files:
            return
        
        file_path = self.md_files[self.current_file_index]
        self.save_file_attributes(file_path)
        messagebox.showinfo("成功", f"已保存: {file_path.name}")
    
    def batch_save(self):
        if not self.md_files:
            return
        
        result = messagebox.askyesno("确认", f"确定要批量修改 {len(self.md_files)} 个文件吗？")
        if result:
            for file_path in self.md_files:
                self.save_file_attributes(file_path)
            messagebox.showinfo("成功", f"已批量保存 {len(self.md_files)} 个文件")
    
    def save_file_attributes(self, file_path):
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析现有的front matter
        front_matter_match = re.search(r'^---\s*\n(.*?)\n---', content, re.DOTALL)
        
        if front_matter_match:
            # 替换现有的front matter
            old_front_matter = front_matter_match.group(0)
            new_front_matter = self.generate_front_matter()
            
            content = content.replace(old_front_matter, new_front_matter)
        else:
            # 添加新的front matter
            new_front_matter = self.generate_front_matter()
            content = new_front_matter + '\n' + content
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
    
    def generate_front_matter(self):
        """根据输入框的值生成front matter"""
        front_matter_lines = ["---"]
        
        for attr in self.attributes:
            entry = self.attribute_entries[attr]
            
            if isinstance(entry, tk.Text):
                value = entry.get(1.0, tk.END).strip()
            else:
                value = entry.get().strip()
            
            if value:
                # 处理数组类型的属性
                if attr in ["tags", "风格", "气质", "体型", "演技"]:
                    # 按行分割，过滤空行
                    items = [line.strip() for line in value.split('\n') if line.strip()]
                    if items:
                        front_matter_lines.append(f"{attr}:")
                        for item in items:
                            front_matter_lines.append(f"  - {item}")
                else:
                    front_matter_lines.append(f"{attr}: {value}")
        
        front_matter_lines.append("---")
        return "\n".join(front_matter_lines)
    
    def previous_file(self):
        if self.md_files and self.current_file_index > 0:
            self.current_file_index -= 1
            self.load_file_attributes()
    
    def next_file(self):
        if self.md_files and self.current_file_index < len(self.md_files) - 1:
            self.current_file_index += 1
            self.load_file_attributes()
    
    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    editor = MarkdownAttributeEditor()
    editor.run()